import $ from 'jquery';

//设置cookie
export function setCookie(cname: string, cvalue: string, exdays: number) {
  var d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  var expires = 'expires=' + d.toUTCString();
  document.cookie = cname + '=' + cvalue + '; ' + expires;
}

//跨域获取cookie(需要获取cookie的地址, 获取cookie的字段)
export async function getDomainCookie(url: string, name: string) {
  return new Promise((resolve, reject) => {
    chrome.cookies.get(
      {
        url,
        name,
      },
      (cookie: unknown) => {
        resolve(cookie);
      },
    );
  });
}

//获取cookie
export function getCookie(cname: string) {
  var name = cname + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
  }
  return '';
}

//清除cookie
export function clearCookie(name: any) {
  setCookie(name, '', -1);
}

/**
 * - ajax请求
 * url地址
 * 请求类型
 * 请求参数
 * 请求头
 */
export async function ajax(
  url: string,
  type: string,
  data: any = null,
  headers: any = null,
) {
  // console.log(url);
  return new Promise((resolve, reject) => {
    $.ajax({
      url,
      type,
      data,
      crossDomain: true, //设置跨域为true
      xhrFields: {
        withCredentials: true, //允许跨域带Cookie
      },
      headers,
      success: (res: unknown) => resolve(res),
      error: (err: unknown) => reject(err),
    });
  });
}
//延迟
export async function timeout(t: number | undefined) {
  return new Promise<void>((resolve, reject) => {
    setTimeout(() => resolve(), t);
  });
}

//获取插件的安装主域名
export const getPluginLocal = () => {
  const str = localStorage.getItem('pluginLocal') || '{}';
  return JSON.parse(str);
};
